/**
 * mysql 数据库访问
 */

import * as mysql from "mysql";

export class DataBaseConnection {
    private readonly config: IDatabaseConfig;
    private readonly connection;

    constructor(config: IDatabaseConfig) {
        this.config = config;
        this.connection = mysql.createConnection({
            host: this.config.location,
            user: this.config.username,
            password: this.config.password,
            database: this.config.database
        });
    }
    /**
     * 数据列表
     */
    dataRows<T>(sql: string, callback: (list: T[]) => void): void {
        this.connection.connect();

        this.connection.on('error', function (err) {
            console.log("错误日志：")
            console.error(err.stack || err);
        });

        this.connection.query(sql, function (error, results, fields) {
            if (error) throw error;

            callback(results);

        });

        this.connection.end();
    }
    /**
     * 影响行数
     */
    affectedRows<T>(sql: string, callback: (affectedRows: number) => void): void {

        this.connection.connect();
        
        this.connection.on('error', function (err) {
            console.log("错误日志：")
            console.error(err.stack || err);
        });

        this.connection.query(sql, function (error, results, fields) {
            if (error) throw error;

            callback(results.affectedRows);

        });

        this.connection.end();
    }
    /**
     * 改变行数
     */
    changedRows(sql: string, callback: (changedRows: number) => void): void {
        this.connection.connect();

        this.connection.on('error', function (err) {
            console.log("错误日志：")
            console.error(err.stack || err);
        });

        this.connection.query(sql, function (error, results, fields) {
            if (error) throw error;

            callback(results.changedRows);

        });

        this.connection.end();
    }
}